import { get as _get, set as _set } from 'lodash';

const vueGlobal = (() => {
  let app = null;
  let keyPath = 'config.globalProperties';

  const checkInstall = function () {
    if (app === null) {
      throw new Error(`vueGlobal is not install`);
    }
  };
  const isExist = function (name) {
    return get(name) !== undefined;
  };

  const install = function (vueApp) {
    app = vueApp;
    const obj = _get(vueApp, keyPath);
    if (!obj || typeof obj !== 'object') {
      keyPath = 'prototype';
    }
  };

  const get = function (name, handle) {
    checkInstall();
    const val = _get(_get(app, keyPath), name);
    if (val !== undefined && typeof handle === 'function') {
      return handle(val);
    }
    return val;
  };

  const set = function (name, value) {
    checkInstall();
    if (isExist(name)) {
      throw new Error(
        'value of ' + name + ': is exist!\n该全局属性重复定义,代码组织逻辑可能存在问题,检查定义是否确保前置'
      );
    }
    _set(_get(app, keyPath), name, value);
  };

  const cover = function (name, value) {
    checkInstall();
    if (!isExist(name)) {
      throw new Error('value of ' + name + ' is not exist! please use set instead');
    }
    _set(_get(app, keyPath), name, value);
  };

  return { install, cover, set, get };
})();

export default vueGlobal;
